﻿using Oplaco.Samples.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Microsoft.WindowsAzure.Storage.Table.DataServices;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.IO;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using System.Diagnostics;
using System.Configuration;
using Oplaco.Samples.WebApi.Providers;
using Oplaco.Samples.Repository;

namespace Oplaco.Samples.WebApi.Controllers
{
    /// <summary>
    /// Files Controller : handles file post and get requests
    /// </summary>
    /// <see cref="http://blogs.msdn.com/b/yaohuang1/archive/2012/07/02/asp-net-web-api-and-azure-blob-storage.aspx"/>
    public class FilesController : ApiController
    {
        #region fields
        private ArticleRepository repos = new ArticleRepository();
        private CloudQueue imagesQueue;
        private static CloudBlobContainer imagesBlobContainer;
        #endregion
        
        public FilesController() {
            InitializeStorage();
        }

        #region Public POST, PUT, DELETE, OPTIONS

        /// <summary>
        /// FileUpload handler
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Task<List<FileItem>> PostMultipartStream()
        {
            Task<List<FileItem>> data = null;

            //validation
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            try
            {
                //process file read into the stream and upload in azure
                var multipartStreamProvider = new AzureBlobStorageMultipartProvider(imagesBlobContainer);
                data = Request.Content.ReadAsMultipartAsync<AzureBlobStorageMultipartProvider>(multipartStreamProvider).ContinueWith<List<FileItem>>(t =>
                {
                    if (t.IsFaulted)
                    {
                        throw t.Exception;
                    }
                    AzureBlobStorageMultipartProvider provider = t.Result;
                    return provider.Files;
                });

                
            }
            catch (Exception ex) {
                Trace.TraceInformation("Something went wrong"+ ex.Message);
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
            return data;
        }


        [HttpGet]
        public FileItem Get(Guid id)
        {
            return null;
        }
        #endregion

        #region private
        private void InitializeStorage()
        {
            // Open storage account using credentials from web.config file.
            var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);

            // Get context object for working with blobs, and 
            // set a default retry policy appropriate for a web user interface.
            var blobClient = storageAccount.CreateCloudBlobClient();
            blobClient.DefaultRequestOptions.RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(3), 3);

            // Get a reference to the blob container.
            imagesBlobContainer = blobClient.GetContainerReference("images");

            // Get context object for working with queues, and 
            // set a default retry policy appropriate for a web user interface.
            CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
            queueClient.DefaultRequestOptions.RetryPolicy = new LinearRetry(TimeSpan.FromSeconds(3), 3);

            // Get a reference to the queue.
            imagesQueue = queueClient.GetQueueReference("images");
        }

        
        #endregion
    }

    
}
